package com.cyx.exam.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cyx.exam.config.ExcelListener;
import com.cyx.exam.entity.Class;
import com.cyx.exam.entity.User;
import com.cyx.exam.entity.UserExcel;
import com.cyx.exam.service.ClassService;
import com.cyx.exam.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cyx
 * @since 2021-03-09
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private ClassService classService;

    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpSession session){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",username)
                .eq("password",password);

        User user1 = userService.getOne(wrapper);
        if(user1 != null){
            session.setAttribute("loginUser", username);
            session.setAttribute("role",user1.getRole());
            session.setAttribute("className",user1.getClassName());
            return "dashboard";
        }else {
            model.addAttribute("msg", "用户名或密码错误");
            return "index";
        }
    }

    @GetMapping("/logout")
    public String Exit(HttpSession session){
        session.invalidate();  //清除session中存放的数据
        return "index";
    }

    @GetMapping("/list")
    public String view(@RequestParam(required = false, defaultValue = "1", value = "pn") Integer pn,
                       Model model) {
        IPage<User> page = userService.selectByPage(pn, 5);
        model.addAttribute("jumpUrl", "list?pn=");
        //此处得到的page对象,包含了current（当前页）,pages（总页数），total（总记录数），records（记录，就是查询到的List集合）
        model.addAttribute("page", page);
        return "user/list";
    }
    @GetMapping("/searchsubmit")
    public String searchsubmit(@RequestParam(required = false, defaultValue = "", value = "name")String name,
                               Model model,
                               @RequestParam(required = false, defaultValue = "1", value = "pn") Integer pn) {
        IPage<User> page = userService.searchByPage(pn, 5, name);
        model.addAttribute("jumpUrl", "list?name="+name+"&pn=");
        model.addAttribute("page", page);
        return "user/list";
    }


    @GetMapping({"/edit/{id}","/edit"})
    public String edit(@PathVariable(value = "id",required = false) Integer id,Model model){
        User user = new User();
        if(id!=null){
            user = userService.getById(id);
            model.addAttribute("type","update");
        }else {
            model.addAttribute("type","insert");
        }
        List<Class> classList = classService.list();

        model.addAttribute("classList",classList);
        model.addAttribute("user",user);
        return "user/edit";
    }

    @PostMapping("/update/{type}")
    public String saveOrUpdate(User user,@PathVariable("type") String type,Model model){
        User one = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getName, user.getName()));
        if(one != null && type.equals("insert")){
            model.addAttribute("msg","该用户已存在");
            return "user/edit";
        }
        userService.saveOrUpdate(user);
        return "redirect:/user/list";
    }

    @GetMapping("/del/{id}")
    public String delete(@PathVariable(value = "id") Integer id){
        userService.delete(id);
        return "redirect:/user/list";
    }

    //通过excel批量导入
    @RequestMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //实例化实现了AnalysisEventListener接口的类
        ExcelListener listener = new ExcelListener();
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
        //读取信息
        excelReader.read(new Sheet(1, 1, UserExcel.class));

        //获取数据
        List<Object> list = listener.getDatas();

        List<UserExcel> userList = new ArrayList<UserExcel>();
        UserExcel userExcel = new UserExcel();
        User user = new User();
        Class aClass = new Class();
        List<String> classNameList = classService.getClassNameList();
        List<String> nameList = userService.getNameList();
        //转换数据类型,并插入到数据库
        for (int i = 0; i < list.size(); i++) {
            userExcel = (UserExcel) list.get(i);
            System.out.println(userExcel);
            BeanUtil.copyProperties(userExcel,user);

            //如果班级不存在先保存班级
            if(!classNameList.contains(user.getClassName())){
                aClass.setName(user.getClassName());
                classService.save(aClass);
                classNameList.add(user.getClassName());
            }
            //保存用户,存在则更新
            if(nameList.contains(user.getName())){
                userService.updateByName(user);
            }else {
                userService.save(user);
                nameList.add(user.getName());
            }


        }
        return "redirect:/user/list";
    }
}

